﻿namespace BM.Tools.WebControls.MForm.Controls.Helper
{
    using System.Collections.Specialized;
    using System.ComponentModel;
    using System.Linq;

    /// <summary>
    /// This class serves as a name value collection to string type converter, that can be used to serialize data using the JSON format.
    /// </summary>
    public class NameValueCollectionJsonConverter : TypeConverter
    {
        /// <summary>
        /// Returns whether this converter canconvert the object to the specified type, using the specified context.
        /// </summary>
        /// <param name="context">
        /// the context
        /// </param>
        /// <param name="destinationType">
        /// the destination type
        /// </param>
        /// <returns>
        /// whether the conversion is possible
        /// </returns>
        public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType)
        {            
            return destinationType == typeof(string);
        }

        /// <summary>
        /// Converts the given value object to the specified type, using the specified context and culture information.
        /// </summary>
        /// <param name="context">
        /// the specified context
        /// </param>
        /// <param name="culture">
        /// the context culture
        /// </param>
        /// <param name="value">
        /// the value object
        /// </param>
        /// <param name="destinationType">
        /// the destination type
        /// </param>
        /// <returns>
        /// the object of the destination type.        
        /// </returns>
        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType)
        {            
            var collection = value as NameValueCollection;
            var keysAndValue = collection.Keys.Cast<string>().Select(key => string.Concat(key, ": '", collection[key], "'")).ToArray();
            return string.Concat("{", string.Join(", ", keysAndValue), "}");
        }
    }
}
